<template>
  <div class="contract-review">
    <!-- 顶部导航 -->
    <div class="top-nav">
      <div class="nav-left">
        <!-- 返回按钮 -->
        <div class="back-button" @click="goBack">
          <i class="el-icon-arrow-left"></i>
          <span>返回</span>
        </div>
        <div class="nav-item active">
          <i class="el-icon-document"></i>
          <span>{{ fileInfo.name || '税务专项代理协议' }}</span>
        </div>
      </div>
      <div class="nav-right">
        <el-button size="small" type="primary" plain icon="el-icon-plus">新审查</el-button>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧编辑区 -->
      <div class="editor-area">
        <div class="editor-tabs">
          <div class="tab active">文档</div>
          <div class="tab">结构</div>
          <div class="tab">注释</div>
        </div>
        <div class="editor-toolbar">
          <span><i class="el-icon-zoom-in"></i></span>
          <span><i class="el-icon-zoom-out"></i></span>
          <span><i class="el-icon-document"></i></span>
          <span><i class="el-icon-edit"></i></span>
          <span><i class="el-icon-search"></i></span>
        </div>
        <div class="editor-content">
          <!-- 加载状态 -->
          <div v-if="isLoading" class="loading-container">
            <div class="loading-spinner"></div>
            <div class="loading-text">文档加载中...</div>
          </div>

          <!-- 错误状态 -->
          <div v-else-if="docError" class="error-container">
            <div class="error-icon"><i class="el-icon-warning-outline"></i></div>
            <div class="error-message">{{ docError }}</div>
            <el-button type="primary" @click="goBack">返回上传页面</el-button>
          </div>

          <!-- 文档内容 -->
          <div v-else class="document-container" v-html="documentHtml"></div>
        </div>

        <div class="editor-footer">
          <div class="footer-left">
            <i class="el-icon-menu"></i>
            <i class="el-icon-data-line"></i>
            <div class="page-info">页面：1/7</div>
            <div class="word-info">字：1/1</div>
            <div class="para-info">段：1</div>
            <div class="line-info">行：1</div>
          </div>
          <div class="footer-right">
            <div class="word-count">字数：2713</div>
            <i class="el-icon-full-screen"></i>
            <div class="zoom">
              <i class="el-icon-zoom-out"></i>
              <span>138%</span>
              <i class="el-icon-zoom-in"></i>
            </div>
            <i class="el-icon-tickets"></i>
            <i class="el-icon-full-screen"></i>
          </div>
        </div>
      </div>

      <!-- 右侧审查区 -->
      <div class="review-area">
        <div class="content-wrapper card-content">
          <!-- 步骤导航 -->
          <div class="steps-nav">
            <div class="step" :class="{ active: currentStep === 0 }" @click="changeStep(0)">
              <div class="step-circle">1</div>
              <div class="step-text">合同概览</div>
            </div>
            <div class="step-line"></div>
            <div class="step" :class="{ active: currentStep === 1 }" @click="changeStep(1)">
              <div class="step-circle">2</div>
              <div class="step-text">审查清单</div>
            </div>
            <div class="step-line"></div>
            <div class="step" :class="{ active: currentStep === 2 }" @click="changeStep(2)">
              <div class="step-circle">3</div>
              <div class="step-text">审查结果</div>
            </div>
          </div>

          <!-- 步骤内容区域 -->
          <!-- 步骤1: 合同概览 -->
          <div v-if="currentStep === 0">
            <div class="review-section">
              <h3 class="section-title">审查方式</h3>

              <div class="form-item">
                <label>合同类型</label>
                <div class="form-input">
                  <el-cascader
                    v-model="reviewSettings.contractType"
                    :options="contractTypeOptions"
                    :props="{ checkStrictly: true, label: 'typeName', value: 'id', children: 'children' }"
                    clearable
                    placeholder="请选择合同类型"
                    style="width: 100%"
                  ></el-cascader>
                </div>
              </div>

              <div class="form-item">
                <label>审查立场</label>
                <div class="form-input">
                  <el-radio-group v-model="reviewSettings.stance">
                    <el-radio label="partyA">甲方立场</el-radio>
                    <el-radio label="partyB">乙方立场</el-radio>
                    <el-radio label="neutral">中立立场</el-radio>
                  </el-radio-group>
                </div>
              </div>

              <div class="form-item">
                <label>审查尺度</label>
                <div class="form-input">
                  <el-radio-group v-model="reviewSettings.intensity">
                    <el-radio label="strong">强势</el-radio>
                    <el-radio label="weak">弱势</el-radio>
                    <el-radio label="equal">均势</el-radio>
                  </el-radio-group>
                </div>
              </div>

              <div class="form-item">
                <label>选择审查清单</label>
                <div class="form-buttons">
                  <el-button
                    :type="activeReviewMethod === 'ai' ? 'primary' : 'default'"
                    class="ai-generate-btn"
                    plain
                    @click="switchReviewMethod('ai')">
                    <i class="el-icon-refresh-right"></i> AI智能生成
                  </el-button>
                  <el-button
                    :type="activeReviewMethod === 'knowledge' ? 'primary' : 'default'"
                    class="knowledge-btn"
                    plain
                    @click="switchReviewMethod('knowledge')">
                    <i class="el-icon-collection"></i> 从知识库选择 <span class="pro-tag">PRO</span>
                  </el-button>
                </div>
                <div v-if="showRuleListSelect" class="rule-list-select">
                  <el-select
                    v-model="selectedRuleList"
                    multiple
                    filterable
                    placeholder="请选择规则清单"
                    style="width: 100%">
                    <el-option
                      v-for="item in ruleListOptions"
                      :key="item.id"
                      :label="item.listName"
                      :value="item.listName">
                    </el-option>
                  </el-select>
                </div>
              </div>
            </div>

            <div class="review-section">
              <h3 class="section-title">合同概览</h3>

              <div class="contract-info">
                <div class="info-item">
                  <div class="info-label">甲方</div>
                  <div class="info-value">{{ contractData.parties.partyA || '请填写甲方信息' }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">乙方</div>
                  <div class="info-value">{{ contractData.parties.partyB || '请填写乙方信息' }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">合同总金额</div>
                  <div class="info-value">{{ contractData.amount || '请填写合同金额' }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">履行期限</div>
                  <div class="info-value">{{ contractData.period || '请填写履行期限' }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">内容概览</div>
                  <div class="info-value content-overview">
                    {{ contractData.summary || '请填写合同内容概览...' }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 步骤2: 审查清单 -->
          <div v-else-if="currentStep === 1" class="step-content">
            <div class="checklist-header">
              <div class="checklist-actions">
                <el-checkbox v-model="selectAllRules" @change="handleSelectAllRules">全部规则 ({{reviewCheckList.length}})</el-checkbox>
                <el-button type="primary" size="small" @click="saveToNewList">保存至新清单</el-button>
              </div>
              <el-button type="primary" class="custom-rule-button" @click="showCustomRuleDialog">自定义审查规则</el-button>
            </div>
            <div class="checklist-content">
              <div v-if="reviewCheckList.length > 0" class="checklist-items">
                <div v-for="(item, index) in reviewCheckList" :key="index" class="checklist-item">
                  <div class="item-header">
                    <div class="item-left">
                      <el-checkbox v-model="item.checked" @change="(val) => handleCheckItem(item, val)" class="item-checkbox"></el-checkbox>
                      <div class="item-number">{{ index + 1 }}</div>
                      <div class="item-title">{{ item.title }}</div>
                      <div v-if="item.ruleSource === 'create'" class="self-created-tag">自设</div>
                      <div v-else-if="item.ruleSource === 'generate'" class="generate-tag">智能</div>
                    </div>
                    <div class="item-right" v-if="item.ruleSource === 'create' || item.ruleSource === 'generate'">
                      <el-button
                        type="danger"
                        size="mini"
                        icon="el-icon-delete"
                        @click.stop="deleteRule(item)">
                        {{ item.ruleSource === 'create' ? '删除' : '移除' }}
                      </el-button>
                    </div>
                  </div>
                  <div class="item-description">{{ item.description }}</div>
                  <!-- 加载状态 -->
                  <div v-if="item.status === 'loading'" class="review-loading">
                    <el-progress type="circle" :percentage="item.progress" :width="80"></el-progress>
                    <span class="loading-text">正在分析中...</span>
                    <span class="loading-subtext">接口调用可能需要1分钟左右，请耐心等待</span>
                  </div>
                  <!-- 审查结果内容 -->
                  <div v-if="item.expanded && item.status === 'completed'" class="review-content">
                    <!-- 审查要点 -->
                    <div v-if="item.results.some(r => r.type === 'summary')" class="review-summary">
                      <div v-for="(result, rIndex) in item.results.filter(r => r.type === 'summary')"
                           :key="'summary-'+rIndex"
                           class="summary-item">
                        <div class="summary-title">{{ result.title }}</div>
                        <div class="summary-content">{{ result.description }}</div>
                      </div>
                    </div>

                    <!-- 风险点列表 -->
                    <div v-if="item.results.some(r => r.type === 'risk')" class="risk-list">
                      <div class="risk-list-header">
                        <div class="risk-count">
                          风险点 {{ item.results.filter(r => r.type === 'risk').length }}
                          <i class="el-icon-arrow-right"></i>
                        </div>
                      </div>

                      <div v-for="(result, rIndex) in item.results.filter(r => r.type === 'risk')"
                           :key="'risk-'+rIndex"
                           class="risk-item-container">
                        <div class="risk-item-header">
                          <div class="risk-item-title">{{ result.title }}</div>
                          <el-tag :type="getRiskLevelType(result.level)" size="small">
                            {{ getRiskLevelText(result.level) }}
                          </el-tag>
                        </div>

                        <div class="risk-item-content">
                          <div class="risk-explanation">{{ result.description }}</div>

                          <!-- 原合同文本 -->
                          <div v-if="result.originalContent" class="contract-text original">
                            <div class="text-header">
                              <span class="text-label">合同原文</span>
                              <el-tag v-if="result.relatedRisk"
                                     :type="result.relatedRisk === '存在风险' ? 'danger' : 'success'"
                                     size="mini">{{ result.relatedRisk }}</el-tag>
                            </div>
                            <div class="text-content">{{ result.originalContent }}</div>
                          </div>

                          <!-- 建议修改文本 -->
                          <div v-if="result.resultContent" class="contract-text suggestion">
                            <div class="text-header">
                              <span class="text-label">建议新增合同条款为</span>
                              <el-button type="text" size="mini" class="edit-btn">
                                <i class="el-icon-edit"></i> 编辑
                              </el-button>
                            </div>
                            <div class="text-content">{{ result.resultContent }}</div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- 其他类型结果 -->
                    <div v-for="(result, rIndex) in item.results.filter(r => !['summary', 'risk'].includes(r.type))"
                         :key="'other-'+rIndex"
                         class="review-detail">
                      <div class="result-header">
                        <div class="result-title">{{ result.title }}</div>
                        <el-tag v-if="result.type === 'suggestion'"
                                type="success"
                                size="small">建议</el-tag>
                        <el-tag v-else-if="result.type === 'comment'"
                                type="info"
                                size="small">评论</el-tag>
                      </div>
                      <div class="result-description">{{ result.description }}</div>
                    </div>
                    <div v-if="item.results && item.results.length === 0" class="empty-result">
                      <i class="el-icon-info-circle"></i>
                      <p>暂无详细结果</p>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-content">
                <i class="el-icon-document-checked"></i>
                <p>暂无审查清单，请回到合同概览步骤生成审查清单</p>
                <el-button type="primary" size="small" @click="changeStep(0)">返回合同概览</el-button>
              </div>
            </div>
          </div>

          <!-- 步骤3: 审查结果 -->
          <div v-else-if="currentStep === 2">
            <div class="review-section">
              <h3 class="section-title">审查结果</h3>
              <div class="result-content">
                <!-- 加载状态 -->
                <div v-if="reviewResultLoading" class="loading-review-result">
                  <i class="el-icon-loading"></i>
                  <p>正在生成审查结果，请稍候...</p>
                  <p class="loading-tip">接口调用可能需要1分钟左右，请耐心等待</p>
                </div>

                <!-- 新的审查结果内容 -->
                <div v-else-if="reviewResult.apiData" class="new-result-summary">
                  <!-- 风险统计 -->
                  <div class="risk-statistics">
                    <div class="risk-stat-item" 
                         :class="{ active: selectedRiskLevel === 'all' }"
                         @click="filterByRiskLevel('all')">
                      <div class="stat-label">总风险数</div>
                      <div class="stat-value">{{ reviewResult.apiData.statistics.total }}</div>
                    </div>
                    <div class="risk-stat-item" 
                         :class="{ active: selectedRiskLevel === 'high' }"
                         @click="filterByRiskLevel('high')">
                      <div class="stat-label">高风险</div>
                      <div class="stat-value high-risk">{{ reviewResult.apiData.statistics.high }}</div>
                    </div>
                    <div class="risk-stat-item" 
                         :class="{ active: selectedRiskLevel === 'medium' }"
                         @click="filterByRiskLevel('medium')">
                      <div class="stat-label">中风险</div>
                      <div class="stat-value medium-risk">{{ reviewResult.apiData.statistics.medium }}</div>
                    </div>
                    <div class="risk-stat-item" 
                         :class="{ active: selectedRiskLevel === 'low' }"
                         @click="filterByRiskLevel('low')">
                      <div class="stat-label">低风险</div>
                      <div class="stat-value low-risk">{{ reviewResult.apiData.statistics.low }}</div>
                    </div>
                  </div>

                  <!-- 审查结果列表 -->
                  <div class="review-results" v-if="filteredResults.length">
                    <el-collapse v-model="activeNames">
                      <el-collapse-item v-for="(result, index) in filteredResults" 
                                       :key="result.resultId" 
                                       :name="index">
                        <template slot="title">
                          <div class="rule-header">
                            <span class="rule-name">审查结果 {{ index + 1 }}</span>
                            <div class="rule-status">
                              <el-tag :type="result.riskLevel === 'high' ? 'danger' : 
                                            result.riskLevel === 'medium' ? 'warning' : 'success'">
                                {{ result.riskLevel === 'high' ? '高风险' : 
                                   result.riskLevel === 'medium' ? '中风险' : '低风险' }}
                              </el-tag>
                            </div>
                          </div>
                        </template>

                        <div class="examine-brief" v-if="result.examineBrief">
                          <h4>审查要点</h4>
                          <p>{{ result.examineBrief }}</p>
                        </div>

                        <!-- 风险点列表 -->
                        <div class="risk-points" v-if="result.riskList && result.riskList.length">
                          <div v-for="(risk, riskIndex) in result.riskList" 
                               :key="riskIndex"
                               class="risk-item"
                               :class="{'has-risk': risk.relatedRisk === '存在风险' || risk.relatedRisk === '存在相关风险'}">
                            <div class="risk-header">
                              <div class="risk-title-section">
                                <span class="risk-number">{{ riskIndex + 1 }}</span>
                                <span class="risk-title">{{ risk.riskBrief }}</span>
                              </div>
                              <span class="risk-status" :class="risk.relatedRisk === '无风险' ? 'success' : 'danger'">
                                {{ risk.relatedRisk }}
                              </span>
                            </div>
                            
                            <div v-if="risk.riskExplain" class="risk-explanation">
                              <div class="section-title">风险说明</div>
                              <div class="section-content">{{ risk.riskExplain }}</div>
                            </div>

                            <div class="content-sections">
                              <div v-if="risk.originalContent" class="original-content">
                                <div class="section-title">原文内容</div>
                                <div class="section-content">{{ risk.originalContent }}</div>
                              </div>

                              <div v-if="risk.resultContent" class="suggested-content">
                                <div class="section-title">建议修改</div>
                                <div class="section-content">{{ risk.resultContent }}</div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                  <div v-else class="empty-content">
                    <i class="el-icon-document"></i>
                    <p>暂无相关风险项</p>
                  </div>
                </div>

                <!-- 旧的审查结果内容 - 保留兼容性 -->
                <div v-else-if="reviewResult.summary" class="result-summary">
                  <h4>总体评价</h4>
                  <p>{{ reviewResult.summary }}</p>

                  <h4>主要风险点</h4>
                  <div v-for="(risk, index) in reviewResult.risks" :key="index" class="risk-item">
                    <div class="risk-title">{{ risk.title }}</div>
                    <div class="risk-description">{{ risk.description }}</div>
                  </div>

                  <h4>修改建议</h4>
                  <div v-for="(suggestion, index) in reviewResult.suggestions" :key="index" class="suggestion-item">
                    <div class="suggestion-title">{{ suggestion.title }}</div>
                    <div class="suggestion-description">{{ suggestion.description }}</div>
                  </div>
                </div>

                <!-- 空内容提示 -->
                <div v-else class="empty-content">
                  <i class="el-icon-s-claim"></i>
                  <p>暂无审查结果</p>
                  <el-button type="primary" size="small" @click="changeStep(0)">返回合同概览</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="review-footer">
          <el-button
            type="primary"
            size="large"
            class="review-btn"
            @click="handleFooterButtonClick"
            :disabled="isFooterButtonDisabled">
            {{ getFooterButtonText() }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 新增、编辑 -->
    <form-edit
      v-if="formEditVisible"
      ref="formEdit"
      :leftTreeData="leftTreesimple"
      @refreshData="queryList"
    ></form-edit>

    <!-- 保存至新清单对话框 -->
    <el-dialog
      title="保存至新清单"
      :visible.sync="saveDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="newListForm" label-width="80px">
        <el-form-item label="清单名称" required>
          <el-input v-model="newListForm.name" placeholder="请输入清单名称"></el-input>
        </el-form-item>
        <el-form-item label="清单描述">
          <el-input type="textarea" v-model="newListForm.description" rows="3" placeholder="请输入清单描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSave">取 消</el-button>
        <el-button type="primary" @click="saveRuleToNewList" :loading="saveRuleLoading">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mammoth from 'mammoth';
import { getContractTypeList, saveContractAndReview } from '@/api/contract';
import {
  rulelistList,
  getRulesByTitle,
  saveRuleListRuleBatch,
  listRuleListRuleWithInfo,
  leftTreeList,
  saveRuleListRule,
  ruleDel,
  deleteRuleListRule
} from '@/api/rule/rule/rule';
import { rulelistInfo, rulelistSave } from '@/api/rule/list/rulelist';
import RuleEdit from '@/views/rule/rule/rule-edit.vue';
import axios from 'axios';
export default {
  name: 'ContractReview',
  components: {
    'form-edit': RuleEdit
  },
  data() {
    return {
      // 当前步骤
      currentStep: 0,
      steps: ['合同概览', '审查清单', '审查结果'],

      // 记录合同ID
      contractId: null,

      // 文档状态
      isLoading: false,
      documentHtml: '',
      docError: null,

      // 全局加载状态
      globalLoading: false,

      // 文件信息
      fileInfo: {
        id: 'demo-file-1',
        name: '示例合同.docx',
        url: 'https://example.com/demo-contract.docx',
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        size: 1024 * 500, // 500KB
        uploadTime: new Date().toISOString()
      },

      // mammoth.js配置选项
      mammothOptions: {
        styleMap: [
          "p[style-name='Heading 1'] => h1:fresh",
          "p[style-name='Heading 2'] => h2:fresh",
          "p[style-name='Heading 3'] => h3:fresh",
          "p[style-name='Title'] => h1.title:fresh",
          "r[style-name='Strong'] => strong"
        ],
        includeDefaultStyleMap: true,
        ignoreEmptyParagraphs: true,
        convertImage: mammoth.images.imgElement(function(image) {
          return image.read("base64").then(function(imageBuffer) {
            return {
              src: "data:" + image.contentType + ";base64," + imageBuffer
            };
          });
        })
      },

      // 高风险
      contractData: {
        title: '',
        parties: {
          partyA: '', // 甲方
          partyB: ''  // 乙方
        },
        amount: '',
        period: '',
        summary: '',
        riskPoints: [],
        reviewComments: []
      },
      reviewSettings: {
        contractType: [],
        stance: 'partyA', // 'partyA', 'partyB', 'neutral'
        intensity: 'strong' // 'strong', 'weak', 'equal'
      },
      activeSection: 'summary',
      reviewStatus: 'pending', // pending, reviewing, reviewed
      currentVersion: 1,
      versions: [
        { id: 1, name: '初始版本', date: new Date().toISOString() }
      ],
      editorConfig: {
        placeholder: '请输入审阅意见...'
      },
      // 当前打开的标记或注释
      currentMarkId: null,
      newComment: '',
      reviewCheckList: [],
      reviewResult: {
        apiData: {
          list: [],
          statistics: {
            total: 0,
            high: 0,
            medium: 0,
            low: 0
          }
        }
      },
      // 风险筛选
      riskFilter: 'all',
      // 合同类型选项
      contractTypeOptions: [],
      // 审查结果加载状态
      reviewResultLoading: false,

      // 规则清单选项
      ruleListOptions: [],
      showRuleListSelect: false,
      selectedRuleList: [],
      activeReviewMethod: 'ai', // 'ai'表示AI智能生成, 'knowledge'表示从知识库选择
      pendingContractType: null,
      contractTypeValue: null,

      // 自定义规则相关
      customRuleDialogVisible: false,
      customRuleForm: {
        ruleName: '',
        ruleDesc: '',
        riskLevel: 'medium'
      },
      customRuleRules: {
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' }
        ],
        ruleDesc: [
          { required: true, message: '请输入规则描述', trigger: 'blur' }
        ]
      },
      previewActiveTab: 'structure',
      formEditVisible: false,
      leftTreesimple: [],
      // 当选中的审查项
      checkedItems: [],
      selectAllRules: false,
      saveDialogVisible: false,
      newListForm: {
        name: '',
        description: ''
      },
      saveRuleLoading: false,
      // Add new property for progress intervals
      progressIntervals: new Map(),
      activeNames: [],
      selectedRiskLevel: 'all', // 当前选中的风险等级
    }
  },
  computed: {
    // 判断底部按钮是否禁用
    isFooterButtonDisabled() {
      // 如果当前是合同概览步骤，且选中从知识库选择但未选择规则清单，则禁用按钮
      if (this.currentStep === 0 &&
          this.activeReviewMethod === 'knowledge' &&
          this.selectedRuleList.length === 0) {
        return true;
      }
      return false;
    },

    // 根据筛选条件过滤风险点
    filteredRisks() {

      if (!this.reviewResult.apiData || !this.reviewResult.apiData.subRisks) {
        return [];
      }

      const risks = this.reviewResult.apiData.subRisks;

      switch (this.riskFilter) {
        case 'risk':
          return risks.filter(risk => risk.relatedRisk === '存在风险');
        case 'no-risk':
          return risks.filter(risk => risk.relatedRisk === '无风险');
        case 'all':
          console.log('all', risks)
        default:
          return risks.filter(risk => risk.riskBrief || risk.originalContent || risk.resultContent);
      }
    },

    // 根据选中的风险等级过滤风险列表
    filteredResults() {
      if (!this.reviewResult.apiData || !this.reviewResult.apiData.list) {
        return [];
      }
      
      if (this.selectedRiskLevel === 'all') {
        return this.reviewResult.apiData.list;
      }
      
      return this.reviewResult.apiData.list.filter(item => 
        item.riskLevel === this.selectedRiskLevel
      );
    }
  },
  created() {
    // 从URL参数获取文件信息
    const {
      fileId,
      fileName,
      fileUrl,
      fileSize,
      contractType,
      contractAmount,
      contractTerm,
      contentSummary,
      partyA,
      partyB,
      currentStep,
      contractId // 添加contractId参数
    } = this.$route.query;

    // 如果从历史记录跳转，已有contractId
    if (contractId) {
      this.contractId = contractId;
      console.log('从历史记录跳转，使用现有contractId:', this.contractId);

      // 获取合同关联的规则列表
      this.getContractRules();
    }

    // 设置文件基本信息
    if (fileId) {
      this.fileInfo.id = fileId;
    }
    if (fileName) {
      this.fileInfo.name = fileName;
    }
    if (fileUrl) {
      this.fileInfo.url = fileUrl;
    } else if (fileId) {
      // 如果没有直接的URL但有fileId，构造URL
      this.fileInfo.url = fileId;
    }
    if (fileSize) {
      this.fileInfo.size = fileSize;
    }
    if (currentStep) {
      console.log('currentStep:', currentStep)
      this.currentStep = parseInt(currentStep, 10) || 0;
    }

    // 设置合同详细信息
    if (partyA || partyB) {
      // 优先使用URL参数中的合同信息
      this.contractData.parties.partyA = partyA || '';
      this.contractData.parties.partyB = partyB || '';
      this.contractData.amount = this.extractAmount(contractAmount) || '';
      this.contractData.period = contractTerm || '';
      this.contractData.summary = contentSummary || '';

      // 如果有合同类型信息，设置合同类型
      if (contractType) {
        // 先记录下合同类型名称，在合同类型选项加载完成后进行匹配
        this.pendingContractType = contractType;
        this.contractTypeValue = contractType;
        // 尝试立即匹配，如果选项已加载
        if (this.contractTypeOptions && this.contractTypeOptions.length > 0) {
          this.reviewSettings.contractType = this.findContractTypeId(contractType);
        }
      }

      // 如果不是从历史记录跳转（没有contractId参数），才需要保存
      if (!this.contractId) {
        // 构造contractDto对象
        // eslint-disable-next-line no-case-declarations
        const contractDto = {
          // 文件信息
          fileName: this.fileInfo.name,
          fileUrl: this.fileInfo.url,
          fileSize: this.fileInfo.size,
          // 合同基本信息
          contractType: this.contractTypeValue || '',
          contractAmount: this.extractAmount(this.contractData.amount),
          contractTerm: this.contractData.period,
          contentSummary: this.contractData.summary || '',
          partyA: this.contractData.parties.partyA,
          partyB: this.contractData.parties.partyB,
          // 审核相关字段
          stance: this.reviewSettings.stance,
          intensity: this.reviewSettings.intensity,
          ruleListId: this.activeReviewMethod === 'knowledge' ? this.getRuleListIds() : '',
          reviewMethod: this.activeReviewMethod,
          currentStep: 0
        };

        saveContractAndReview(contractDto).then(response => {
          if (response && response.code === 0 && response.data) {
            // 记录contractId
            if (response.data.contractId) {
              this.contractId = response.data.contractId;
              console.log('获取到contractId:', this.contractId);
            }
          } else {
            this.$message.error(response.msg || '保存失败');
          }
        }).catch(error => {
          console.error('保存合同信息和审核记录出错:', error);
          this.$message.error('保存失败: ' + (error.message || '未知错误'));
        });
      }

      this.loadDocument();
    } else if (this.fileInfo.url) {
      // 如果没有合同信息但有文件URL，尝试解析文档
      this.loadDocument();
    } else {
      this.isLoading = false;
    }

    // 获取合同类型数据
    this.fetchContractTypes();
  },
  methods: {
    /**
     * 切换步骤
     * @param {number} stepIndex 步骤索引
     */
    async changeStep(step) {
      if (step === this.currentStep) return;
      
      if (step === 2) {
        // 获取审查结果
        try {
          const uploadInstance = axios.create({
            baseURL: 'http://localhost:8481',
            timeout: 0,
            headers: {
              Authorization: 'Bearer ' + (localStorage.getItem("token") || this.$store.state.token)
            }
          });

          const response = await uploadInstance.get('/api/contract-review-results/listAll', {
            params: {
              contractId: this.contractId
            },
            timeout: 1300000 // 10分钟超时
          });

          if (response.data.code === 0) {
            // 将获取到的所有审查结果保存到数据中
            this.reviewResult.apiData = response.data.data;
            this.$message.success('审查结果获取成功');
            this.currentStep = step;
          } else {
            throw new Error(response.data.message || '获取审查结果失败');
          }
        } catch (error) {
          console.error('获取审查结果列表失败:', error);
          this.$message.error('获取审查结果失败: ' + (error.message || '未知错误'));
        }
      } else {
        this.currentStep = step;
      }
    },

    /**
     * 根据合同类型名称查找对应的合同类型ID
     * @param {string} typeName 合同类型名称
     * @returns {Array} 合同类型ID路径数组
     */
    findContractTypeId(typeName) {
      if (!typeName || !this.contractTypeOptions || !this.contractTypeOptions.length) {
        console.log('合同类型查找条件不满足:', { typeName, hasOptions: !!this.contractTypeOptions });
        return [];
      }

      // 递归搜索合同类型
      const findTypeId = (options, name) => {
        for (const option of options) {

          // 检查当前节点 - 增加不区分大小写的比较
          const optionName = option.typeName || option.name || '';
          const matchesName = optionName.toLowerCase() === name.toLowerCase();

          if (matchesName && option.id) {
            console.log('找到匹配的合同类型:', option);
            return [option.id];
          }

          // 检查子节点
          if (option.children && option.children.length) {
            const found = findTypeId(option.children, name);
            if (found.length) {
              // 返回当前节点ID和子节点路径，形成完整路径
              return [option.id, ...found];
            }
          }
        }
        return [];
      };

      // 尝试精确匹配
      let result = findTypeId(this.contractTypeOptions, typeName);

      // 如果没找到，尝试查找包含该名称的选项
      if (!result.length) {
        console.log('精确匹配失败，尝试包含匹配');
        const findByContains = (options, name) => {
          for (const option of options) {
            const optionName = option.typeName || option.name || '';
            if (optionName.toLowerCase().includes(name.toLowerCase()) && option.id) {
              console.log('找到包含匹配的合同类型:', option);
              return [option.id];
            }

            if (option.children && option.children.length) {
              const found = findByContains(option.children, name);
              if (found.length) {
                return [option.id, ...found];
              }
            }
          }
          return [];
        };

        result = findByContains(this.contractTypeOptions, typeName);
      }

      console.log('合同类型查找结果:', result);
      return result;
    },

    /**
     * 加载并解析文档
     */
    async loadDocument() {
      try {
        this.isLoading = true;
        this.docError = null;

        // 使用文件的实际URL
        const docUrl = this.fileInfo.url;

        // 获取文档
        const response = await fetch(docUrl);
        if (!response.ok) {
          throw new Error(`无法获取文档: ${response.statusText}`);
        }

        const arrayBuffer = await response.arrayBuffer();

        // 使用mammoth.js将Word文档转换为HTML
        const result = await mammoth.convertToHtml({ arrayBuffer }, this.mammothOptions);

        // 输出警告信息
        if (result.messages && result.messages.length > 0) {
          console.warn('Mammoth.js警告:', result.messages);
        }

        this.documentHtml = result.value;

        // 解析合同数据
        this.extractContractData(result.value);

      } catch (error) {
        console.error('文档处理错误:', error);
        this.docError = error.message || '文档处理失败，请重试';
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * 从文档内容中提取合同数据
     * @param {string} htmlContent HTML格式的文档内容
     */
    extractContractData(htmlContent) {
      if (!htmlContent) return;

      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlContent, 'text/html');

      // 提取标题 - 通常是文档的第一个大标题
      const headings = doc.querySelectorAll('h1, h2');
      if (headings.length > 0) {
        this.contractData.title = headings[0].textContent.trim();
      }
    },

    /**
     * 返回上一页
     */
    goBack() {
      // 如果是从历史记录进入，返回到上一页
      if (this.$route.query.contractId) {
        this.$router.go(-1);
      } else {
        // 如果是直接上传进入，返回到上传页面
        this.$router.push('/contract/upload/ContractUpload');
      }
    },

    /**
     * 获取状态文本
     * @param {string} status 状态码
     * @returns {string} 状态文本
     */
    getStatusText(status) {
      const statusMap = {
        'pass': '通过',
        'fail': '不通过',
        'warning': '需注意',
        'pending': '待审查'
      };
      return statusMap[status] || '待审查';
    },

    /**
     * 生成审查清单
     */
    generateReviewList: async function () {
      // 显示加载提示
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在生成审查清单...',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      });

      try {
        // 清空现有的审查清单
        this.reviewCheckList = [];
        this.contractRuleList = [];

        // 根据合同类型确定需要使用的规则分组
        let contractType = '';
        if (this.reviewSettings.contractType && this.reviewSettings.contractType.length > 0) {
          // 获取最后一级选中的合同类型
          const typeId = this.reviewSettings.contractType[this.reviewSettings.contractType.length - 1];

          // 查找对应的类型名称
          const findTypeName = (options, id) => {
            for (const option of options) {
              if (option.id === id) {
                return option.typeName || option.name;
              }
              if (option.children) {
                const found = findTypeName(option.children, id);
                if (found) return found;
              }
            }
            return null;
          };

          contractType = findTypeName(this.contractTypeOptions, typeId) || '买卖合同';
        } else {
          // 默认使用买卖合同规则
          contractType = '买卖合同';
        }

        console.log('使用的合同类型:', contractType);

        // 调用API获取该类型的规则列表
        const response = await getRulesByTitle(contractType);

        if (response && response.code === 0 && response.data) {
          const rules = response.data;
          console.log('获取到的规则列表:', rules);

          // 根据规则生成审查清单
          if (Array.isArray(rules) && rules.length > 0) {
            for (const rule of rules) {
              if (!rule || typeof rule !== 'object') continue;

              // 设置默认状态
              let status = 'pending';

              // 将规则添加到审查清单
              this.reviewCheckList.push({
                title: rule.ruleName || `规则 ${rule.id}`,
                description: rule.ruleDesc || '无描述',
                status: status,
                ruleId: rule.id,
                ruleType: rule.ruleType
              });
              this.contractRuleList.push({
                ruleId: rule.id,
                contractId: this.contractId
              });
            }
            console.log('成功获取规则清单详情', this.contractRuleList);
            await saveRuleListRuleBatch(this.contractRuleList);
          } else {
            this.$message.warning(`未找到${contractType}相关的审查规则`);
          }
        } else {
          this.$message.warning('获取规则列表失败');
        }

        // 关闭加载提示
        loadingInstance.close();
        this.$message.success(`已生成 ${this.reviewCheckList.length} 项审查清单`);

        // 自动跳转到审查清单页面
        this.changeStep(1);
      } catch (error) {
        console.error('生成审查清单出错:', error);

        // 关闭加载提示
        loadingInstance.close();
        this.$message.error('生成审查清单出错');

        // 使用默认清单
        this.reviewCheckList = [
          {
            title: '生成审查清单失败',
            description: '获取规则列表时发生错误，请重试',
            status: 'fail'
          }
        ];

        // 自动跳转到审查清单页面
        this.changeStep(1);
      }
    },

    /**
     * 生成审查结果
     */
    async generateReviewResult() {
      // 设置加载状态
     //  this.reviewResultLoading = true;

      // // 显示全局加载提示
       this.globalLoading = true;
      // const loadingInstance = this.$loading({
      //   lock: true,
      //   text: '正在调用审查接口，预计需要1分钟左右...',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(255, 255, 255, 0.8)'
      // });

      try {
        // 获取选中的规则清单
        const selectedRules = this.reviewCheckList.filter(item => item.checked);

        if (selectedRules.length === 0) {
          this.$message.warning('请至少选择一个规则清单进行审查');
          loadingInstance.close();
          this.globalLoading = false;
          return;
        }

        // 获取必要参数
        const fileUrl = this.$route.query.fileUrl;
        const userId = localStorage.getItem('userId') || 'abc-1244';

        // 获取审查立场
        let standpoint = '甲方';
        switch(this.reviewSettings.stance) {
          case 'partyA':
            standpoint = '甲方';
            break;
          case 'partyB':
            standpoint = '乙方';
            break;
          case 'neutral':
            standpoint = '中立';
            break;
        }

        // 获取审查尺度
        let reviewScale = '强';
        switch(this.reviewSettings.intensity) {
          case 'strong':
            reviewScale = '强';
            break;
          case 'weak':
            reviewScale = '弱';
            break;
          case 'equal':
            reviewScale = '均势';
            break;
        }

        // 为每个选中的规则创建审查请求
        const checkRequests = selectedRules.map(async rule => {
          try {
            // 更新规则状态为加载中
            rule.status = 'loading';
            rule.progress = 0;

            // 开始进度条模拟
            this.startProgressSimulation(rule);

            // 构造请求参数
            const params = {
              fileUrl,
              userId,
              standpoint,
              reviewScale,
              riskId: rule.ruleId,
              ruleId: rule.id,
              contractId: this.contractId,
                
            };


            const uploadInstance = axios.create({
              baseURL: 'http://localhost:8481',
                timeout: 0,  // 0表示无超时限制
              headers: {
                Authorization: 'Bearer ' + (localStorage.getItem("token") || Store.state.token)
              }
            });

            // 发送请求
            const response = await uploadInstance.post('/api/files/checkContract', params, {
              timeout: 1300000, // 10分钟超时
              headers: {
                'authorization': 'Bearer '+ localStorage.getItem('token') || ''
              }
            });

            // 处理响应
            if (response.data.code === 0) {
              this.reviewResultLoading = false;
              rule.status = 'completed';
              rule.results = this.formatResults(response.data.data);
              rule.expanded = true; // 自动展开结果

              // 保存API原始数据用于审查结果页面
              this.reviewResult.apiData = response.data.data;

              this.$message.success(`规则"${rule.title}"审查完成`);
            } else {
              throw new Error(response.data.message || '审查失败');
            }
          } catch (error) {
            console.error('规则审查失败:', error);
            rule.status = 'error';
            rule.error = error.message || '审查过程中出现错误';
            this.$message.error(`规则"${rule.title}"审查失败: ${rule.error}`);
          } finally {
            // 停止进度条模拟
            this.stopProgressSimulation(rule);
          }
        });




        // 并行执行所有请求
        await Promise.allSettled(checkRequests);

        // 获取所有审查结果
        try {
          const uploadInstance = axios.create({
            baseURL: 'http://localhost:8481',
            timeout: 0,
            headers: {
              Authorization: 'Bearer ' + (localStorage.getItem("token") || Store.state.token)
            }
          });

          const response = await uploadInstance.get('/api/contract-review-results/listAll', {
            params: {
              contractId: this.contractId
            },
            timeout: 1300000, // 10分钟超时
       
          });

          if (response.data.code === 0) {
            // 将获取到的所有审查结果保存到数据中
            this.reviewResult.apiData = response.data.data;
            this.$message.success('审查结果获取成功');
          } else {
            throw new Error(response.data.message || '获取审查结果失败');
          }
        } catch (error) {
          console.error('获取审查结果列表失败:', error);
          this.$message.error('获取审查结果失败: ' + (error.message || '未知错误'));
        }

        // 更新步骤
        this.currentStep = 2;

        
      } catch (error) {
        console.error('生成审查结果出错:', error);
        this.$message.error('生成审查结果失败: ' + (error.message || '未知错误'));
      } finally {
        // 关闭全局加载提示
        if (loadingInstance) {
          loadingInstance.close();
        }
        this.globalLoading = false;
        this.reviewResultLoading = false;
      }
    },

    /**
     * 获取底部按钮文本
     * @returns {string} 按钮文本
     */
    getFooterButtonText() {
      switch (this.currentStep) {
        case 0:
          return '生成审查清单';
        case 1:
          return '生成审查结果';
        case 2:
          return '导出审查报告';
        default:
          return '下一步';
      }
    },

    /**
     * 处理底部按钮点击
     */
    handleFooterButtonClick() {
      switch (this.currentStep) {
        case 0:
          // 构造contractDto对象
          // eslint-disable-next-line no-case-declarations
          const contractDto = {
            // 如果有contractId，加入参数
            contractId: this.contractId || undefined,
            // 文件信息
            fileName: this.fileInfo.name,
            fileUrl: this.fileInfo.url,
            fileSize: this.fileInfo.size,
            // 合同基本信息
            contractType: this.contractTypeValue || '',
            contractAmount: this.extractAmount(this.contractData.amount),
            contractTerm: this.contractData.period,
            contentSummary: this.contractData.summary || this.$route.query.contentSummary || '',
            partyA: this.contractData.parties.partyA,
            partyB: this.contractData.parties.partyB,
            // 审核相关字段
            stance: this.reviewSettings.stance,
            intensity: this.reviewSettings.intensity,
            ruleListId: this.activeReviewMethod === 'knowledge' ? this.getRuleListIds() : '',
            reviewMethod: this.activeReviewMethod,
            currentStep: 1
          };

          // 调用保存方法
          saveContractAndReview(contractDto).then(response => {
            if (response && response.code === 0 && response.data) {
              // 记录contractId
              if (response.data.contractId) {
                this.contractId = response.data.contractId;
                console.log('获取到contractId:', this.contractId);
              }
            } else {
              this.$message.error(response.msg || '保存失败');
            }
          }).catch(error => {
            console.error('保存合同信息和审核记录出错:', error);
            this.$message.error('保存失败: ' + (error.message || '未知错误'));
          });
          if (this.activeReviewMethod === 'knowledge' && this.selectedRuleList.length > 0) {
            // 使用选定的规则清单生成审查清单
            this.generateReviewListFromRules();
          } else {
            // 使用AI生成审查清单
            this.generateReviewList();
          }
          break;
        case 1:
          this.generateReviewResult();
          break;
        case 2:
          this.$message.success('审查报告已导出');
          break;
      }
    },

    /**
     * 获取合同类型列表
     */
    async fetchContractTypes() {
      try {
        // 调用API方法获取合同类型数据
        const response = await getContractTypeList();

        // 检查响应数据
        if (response && response.code === 0) {
          if (Array.isArray(response.data)) {
            this.contractTypeOptions = response.data;
            console.log('成功获取合同类型数据');

            // 如果有待处理的合同类型，现在进行匹配
            if (this.pendingContractType) {
              console.log('处理待匹配的合同类型:', this.pendingContractType);
              this.reviewSettings.contractType = this.findContractTypeId(this.pendingContractType);
              this.pendingContractType = null;
            }
          } else {
            console.warn('合同类型数据格式不正确:', response.data);
            this.setDefaultContractTypes();
          }
        } else {
          console.warn('获取合同类型失败:', response);
          this.setDefaultContractTypes();
        }
      } catch (error) {
        console.error('获取合同类型出错:', error);
        // 使用默认数据
        this.setDefaultContractTypes();
      }
    },

    /**
     * 设置默认合同类型数据
     */
    setDefaultContractTypes() {
      this.contractTypeOptions = [
        {
          id: '1',
          name: '委托合同',
          children: [
            { id: '1-1', name: '代理合同' },
            { id: '1-2', name: '咨询合同' }
          ]
        },
        {
          id: '2',
          name: '买卖合同',
          children: [
            { id: '2-1', name: '货物买卖合同' },
            { id: '2-2', name: '设备买卖合同' }
          ]
        },
        {
          id: '3',
          name: '服务合同',
          children: [
            { id: '3-1', name: '技术服务合同' },
            { id: '3-2', name: '培训服务合同' }
          ]
        },
        {
          id: '4',
          name: '租赁合同',
          children: [
            { id: '4-1', name: '房屋租赁合同' },
            { id: '4-2', name: '设备租赁合同' }
          ]
        },
        {
          id: '5',
          name: '劳动合同',
          children: [
            { id: '5-1', name: '固定期限劳动合同' },
            { id: '5-2', name: '无固定期限劳动合同' }
          ]
        }
      ];

      // 如果有待处理的合同类型，设置它
      if (this.pendingContractType) {
        console.log('使用默认数据处理待匹配的合同类型:', this.pendingContractType);
        this.reviewSettings.contractType = this.findContractTypeId(this.pendingContractType);
        this.pendingContractType = null;
      }
    },

    /**
     * 显示规则选择器
     */
    showRuleSelector() {
      this.showRuleListSelect = !this.showRuleListSelect;
      if (this.showRuleListSelect && this.ruleListOptions.length === 0) {
        this.fetchRuleList();
      }
    },

    /**
     * 获取规则清单列表
     */
    async fetchRuleList() {
      try {
        const response = await rulelistList();
        if (response && response.code === 0) {
          this.ruleListOptions = response.data || [];
          console.log('成功获取规则清单数据');
        } else {
          console.warn('获取规则清单失败:', response);
          this.$message.warning('获取规则清单失败');
        }
      } catch (error) {
        console.error('获取规则清单出错:', error);
        this.$message.error('获取规则清单出错');
      }
    },

    /**
     * 根据规则清单生成审查清单
     */
    async generateReviewListFromRules() {
      // 创建加载提示
      let loadingInstance = null;
      try {
        loadingInstance = this.$loading({
          lock: true,
          text: '正在根据选定规则生成审查清单...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.7)'
        });
      } catch (e) {
        console.error('创建loading提示失败:', e);
        // 使用普通消息替代
        this.$message({
          message: '正在生成审查清单...',
          type: 'info'
        });
      }

      try {
        // 清空现有的审查清单
        this.reviewCheckList = [];
        this.contractRuleList = [];

        // 获取每个选定规则清单的详细信息
        if (Array.isArray(this.selectedRuleList)) {
          for (let i = 0; i < this.selectedRuleList.length; i++) {
            const listName = this.selectedRuleList[i];
            if (!listName) continue;

            // 查找规则清单ID
            let ruleListId = null;
            if (Array.isArray(this.ruleListOptions)) {
              const foundRule = this.ruleListOptions.find(item => item && typeof item === 'object' && item.listName === listName);
              if (foundRule && foundRule.id) {
                ruleListId = foundRule.id;
              }
            }

            if (ruleListId) {
              try {
                console.log('正在获取规则清单详情，ID:', ruleListId);

                const response = await rulelistInfo(ruleListId);

                if (response && typeof response === 'object' && response.code === 0 && response.data) {
                  const ruleListDetail = response.data;

                  // 处理规则清单中的规则
                  if (ruleListDetail && typeof ruleListDetail === 'object' &&
                      ruleListDetail.rules && Array.isArray(ruleListDetail.rules)) {

                    for (let j = 0; j < ruleListDetail.rules.length; j++) {
                      const rule = ruleListDetail.rules[j];
                      if (!rule || typeof rule !== 'object') continue;

                      // 设置默认状态
                      let status = 'pending';

                      // 安全地获取字段值
                      const ruleName = rule.ruleName && typeof rule.ruleName === 'string' ? rule.ruleName : '';
                      const ruleDesc = rule.ruleDesc && typeof rule.ruleDesc === 'string' ? rule.ruleDesc : '';
                      const ruleId = rule.id || '';
                      const ruleType = rule.ruleType || '';

                      // 将规则添加到审查清单
                      this.reviewCheckList.push({
                        title: ruleName || `规则 ${ruleId}`,
                        description: ruleDesc || '无描述',
                        status: status,
                        ruleId: ruleId,
                        ruleType: ruleType,
                        ruleSource: rule.ruleSource || ''
                      });

                      this.contractRuleList.push({
                        ruleId: rule.id,
                        contractId: this.contractId
                      });
                    }
                    console.log('成功获取规则清单详情', this.contractRuleList);
                    await saveRuleListRuleBatch(this.contractRuleList);
                  }
                } else {
                  console.warn('获取规则清单详情失败:', response);
                  this.$message.warning(`获取规则清单"${listName}"详情失败`);
                }
              } catch (requestError) {
                console.error(`获取规则清单"${listName}"详情错误:`, requestError);
                this.$message.warning(`获取规则清单"${listName}"详情出错`);
              }
            }
          }
        }

        // 如果没有获取到任何规则，显示提示
        if (!this.reviewCheckList.length) {
          this.$message.warning('未能获取到有效的规则清单内容');
        }

        // 关闭加载提示
        if (loadingInstance) {
          try {
            loadingInstance.close();
          } catch (e) {
            console.error('关闭loading提示失败:', e);
          }
        }

        this.$message.success(`已生成 ${this.reviewCheckList.length} 项审查清单`);

        // 自动跳转到审查清单页面
        this.changeStep(1);
      } catch (error) {
        console.error('生成审查清单出错:', error);

        // 关闭加载提示
        if (loadingInstance) {
          try {
            loadingInstance.close();
          } catch (e) {
            console.error('关闭loading提示失败:', e);
          }
        }

        this.$message.error('生成审查清单出错');

        // 添加错误提示项
        this.reviewCheckList = [
          {
            title: '生成审查清单失败',
            description: '获取规则清单详情时发生错误',
            status: 'fail'
          }
        ];
      }
    },

    /**
     * 切换审查方法
     * @param {string} method - 'ai'或'knowledge'
     */
    switchReviewMethod(method) {
      this.activeReviewMethod = method;

      if (method === 'knowledge') {
        this.showRuleListSelect = true;
        if (this.ruleListOptions.length === 0) {
          this.fetchRuleList();
        }
      } else {
        this.showRuleListSelect = false;
      }
    },

    /**
     * 根据合同类型ID查找合同类型名称
     * @param {string|number} typeId 合同类型ID
     * @returns {string} 合同类型名称
     */
    findContractTypeName(typeId) {
      if (!typeId || !this.contractTypeOptions || !this.contractTypeOptions.length) {
        return '';
      }

      // 递归搜索合同类型名称
      const findTypeName = (options, id) => {
        for (const option of options) {
          if (option.id == id) {
            return option.typeName || option.name || '';
          }

          // 检查子节点
          if (option.children && option.children.length) {
            const found = findTypeName(option.children, id);
            if (found) {
              return found;
            }
          }
        }
        return '';
      };

      return findTypeName(this.contractTypeOptions, typeId);
    },

    /**
     * 获取选定的规则清单ID
     * @returns {string} 规则清单ID列表，以逗号分隔
     */
    getRuleListIds() {
      if (!this.selectedRuleList || !Array.isArray(this.selectedRuleList)) {
        return '';
      }
      return this.selectedRuleList.map(name => {
        const found = this.ruleListOptions.find(item => item && typeof item === 'object' && item.listName === name);
        return found && found.id ? found.id.toString() : '';
      }).filter(id => id).join(',');
    },

    /**
     * 从金额字符串中提取纯数字部分
     * @param {string} amountStr 包含金额的字符串，如"人民币80100.00元"
     * @returns {string} 纯数字金额
     */
    extractAmount(amountStr) {
      if (!amountStr) return '';
      // 使用正则表达式提取数字和小数点
      const matches = amountStr.match(/\d+(\.\d+)?/);
      return matches ? matches[0] : '';
    },

    /**
     * 获取合同关联的规则列表
     */
    async getContractRules() {
      try {
        this.historyLoading = true;
        console.log('正在获取合同关联规则, contractId:', this.contractId);

        const response = await listRuleListRuleWithInfo({"contractId" : this.contractId});

        if (response && response.code === 0 && response.data) {
          console.log('获取到合同关联规则:', response.data);

          // 清空现有的审查清单
          this.reviewCheckList = [];

          // 处理返回的规则数据
          if (Array.isArray(response.data)) {
            response.data.forEach(rule => {
              if (!rule) return;

              this.reviewCheckList.push({
                title: rule.ruleName || `规则 ${rule.ruleId}`,
                description: rule.ruleDesc || '无描述',
                status: rule.status || 'pending',
                ruleId: rule.ruleId,
                ruleType: rule.ruleType,
                ruleSource: rule.ruleSource || ''
              });
            });
          }

          console.log('成功加载历史规则清单，共', this.reviewCheckList.length, '条');
        } else {
          console.warn('获取合同关联规则失败:', response);
        }
      } catch (error) {
        console.error('获取合同关联规则出错:', error);
      } finally {
        this.historyLoading = false;
      }
    },

    /**
     * 获取风险级别对应的标签类型
     */
    getRiskLevelType(level) {
      if (level === 'high') return 'danger';
      if (level === 'medium') return 'warning';
      if (level === 'low') return 'info';
      return 'warning';
    },

    /**
     * 获取风险级别对应的中文文本
     */
    getRiskLevelText(level) {
      if (level === 'high') return '高风险';
      if (level === 'medium') return '中风险';
      if (level === 'low') return '低风险';
      return '中风险';
    },

    /**
     * 显示自定义审查规则对话框
     */
    showCustomRuleDialog() {
      this.formEditVisible = true;

      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '加载规则分组',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      });

      // 调用API获取规则分组数据
      leftTreeList().then((resp) => {
        if (resp.code === 0 && resp.data) {
          console.log('获取规则分组成功:', resp.data);
          this.leftTreesimple = resp.data;

          // 访问组件实例并初始化，默认选中第一个分组
          this.$nextTick(() => {
            if (this.$refs.formEdit) {
              // 如果有规则分组，选择第一个，否则使用默认分组
              if (this.leftTreesimple && this.leftTreesimple.length > 0) {
                // 获取第一个有效分组
                let firstGroup = this.leftTreesimple[0];
                // 如果第一项是"全部"(-1)且有其他分组，则选择第二个
                if (firstGroup.id === -1 && this.leftTreesimple.length > 1) {
                  firstGroup = this.leftTreesimple[1];
                }

                console.log('初始化规则编辑器，选择分组:', firstGroup);
                this.$refs.formEdit.init(null, firstGroup.id, firstGroup.title);
              } else {
                // 没有分组时使用默认值
                this.$refs.formEdit.init(null, 'custom', '自定义规则分组');
              }
            }
          });
        } else {
          console.warn('获取规则分组失败:', resp);
          this.$message.warning('获取规则分组失败，使用默认分组');

          // 使用默认分组
          this.leftTreesimple = [{
            id: 'custom',
            title: '自定义规则分组'
          }];

          // 初始化组件
          this.$nextTick(() => {
            if (this.$refs.formEdit) {
              this.$refs.formEdit.init(null, 'custom', '自定义规则分组');
            }
          });
        }
      }).catch(error => {
        console.error('获取规则分组出错:', error);
        this.$message.error('获取规则分组出错');

        // 使用默认分组
        this.leftTreesimple = [{
          id: 'custom',
          title: '自定义规则分组'
        }];

        // 初始化组件
        this.$nextTick(() => {
          if (this.$refs.formEdit) {
            this.$refs.formEdit.init(null, 'custom', '自定义规则分组');
          }
        });
      }).finally(() => {
        // 关闭加载状态
        loading.close();
      });
    },

    /**
     * 查询列表 - 处理form-edit组件回调
     * @param {Object} ruleData - 规则编辑组件返回的规则数据
     */
    async queryList(ruleData) {
      this.formEditVisible = false;

      // 检查是否有规则数据传入
      if (ruleData && typeof ruleData === 'object' && ruleData.id) {
        console.log('收到规则数据:', ruleData);

        try {
          // 添加到审查清单
          const newRuleItem = {
            title: ruleData.ruleName,
            description: ruleData.ruleDesc || '',
            status: 'pending',
            ruleId: ruleData.id,
            ruleType: ruleData.ruleType || 'custom',
            riskLevel: ruleData.riskLevel || 'medium',
            ruleSource: ruleData.ruleSource || 'create'
          };

          this.reviewCheckList.push(newRuleItem);

          // 如果有contractId，保存规则与合同的关联
          if (this.contractId) {
            // 准备关联数据
            const ruleContractRelation = {
              ruleId: ruleData.id,
              contractId: this.contractId
            };

            // 保存关联数据
            console.log('保存规则与合同关联:', ruleContractRelation);
            const saveResult = await saveRuleListRule(ruleContractRelation);

            if (saveResult && saveResult.code === 0) {
              console.log('规则关联保存成功');
            } else {
              console.warn('规则关联保存失败:', saveResult);
              this.$message.warning('规则已添加到清单，但保存关联数据失败');
            }
          } else {
            console.warn('未找到contractId，无法保存规则关联');
            this.$message.success('规则已添加到清单');
          }
        } catch (error) {
          console.error('保存规则关联出错:', error);
          this.$message.warning('规则已添加到清单，但保存数据出错');
        }
      } else if (ruleData && ruleData.current) {
        // 处理分页事件，按原有逻辑执行
        console.log('处理分页事件:', ruleData);
      } else {
        // 没有传入数据或传入数据不合规，可能是普通的关闭事件
        console.log('未接收到有效规则数据');
        this.$message.success('操作已完成');
      }
    },

    /**
     * 处理审查项选中状态变更
     * @param {Object} item - 审查项
     * @param {Boolean} checked - 是否选中
     */
    handleCheckItem(item, checked) {
      item.checked = checked;
      // 更新全选状态
      this.updateSelectAllStatus();
      console.log('当前选中的审查项数量:', this.reviewCheckList.filter(item => item.checked).length);
    },
    updateSelectAllStatus() {
      // 如果所有项都被选中，则全选状态为true，否则为false
      this.selectAllRules = this.reviewCheckList.length > 0 && this.reviewCheckList.every(item => item.checked);
    },
    handleSelectAllRules(val) {
      this.reviewCheckList.forEach(item => {
        item.checked = val;
      });
    },
    saveToNewList() {
      const selectedItems = this.reviewCheckList.filter(item => item.checked);
      if (selectedItems.length === 0) {
        this.$message.warning('请至少选择一个规则');
        return;
      }

      this.saveDialogVisible = true;
      this.newListForm = {
        name: '',
        description: ''
      };
    },

    saveRuleToNewList() {
      if (!this.newListForm.name) {
        this.$message.warning('请输入清单名称');
        return;
      }

      this.saveRuleLoading = true;
      const selectedItems = this.reviewCheckList.filter(item => item.checked);
      const ruleIds = selectedItems.map(item => item.ruleId);


      // 保存规则清单信息
      rulelistSave({
        listName: this.newListForm.name,
        listBrief: this.newListForm.description,
        ruleList: ruleIds
      }).then(resp => {
        if (resp.code === 0) {
          this.$message.success('规则清单保存成功');
          this.saveDialogVisible = false;
        } else {
          this.$message.error(resp.msg || '规则清单保存失败');
          this.saveRuleLoading = false;
        }
      }).catch(error => {
        console.error('保存规则清单失败:', error);
        this.$message.error('规则清单保存失败');
        this.saveRuleLoading = false;
      });
    },

    cancelSave() {
      this.saveDialogVisible = false;
    },

    /**
     * 删除或移除规则
     * @param {Object} rule - 要处理的规则
     */
    async deleteRule(rule) {
      try {
        // 确认删除消息根据规则类型显示不同内容
        const confirmMsg = rule.ruleSource === 'create'
          ? `确认删除规则 "${rule.title}"?`
          : `确认从清单中移除规则 "${rule.title}"?`;

        const confirmTitle = rule.ruleSource === 'create' ? '删除规则' : '移除规则';

        await this.$confirm(confirmMsg, confirmTitle, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        let success = false;

        // 根据规则来源决定删除策略
        if (rule.ruleSource === 'create') {
          // 自设规则: 删除规则本身及其关联
          const delResponse = await ruleDel(rule.ruleId);

          if (delResponse && delResponse.code === 0) {
            success = true;
            // 规则本身删除成功，关联关系会自动删除，不需要额外处理
          } else {
            this.$message.error(delResponse.msg || '删除失败');
          }
        } else {
          // 系统生成规则: 只删除关联关系
          success = true; // 假设成功，除非后续操作失败
        }

        // 如果操作成功或是系统生成规则，处理关联关系
        if (success || rule.ruleSource === 'generate') {
          if (this.contractId) {
            try {
              // 查找关联记录ID
              const response = await listRuleListRuleWithInfo({
                contractId: this.contractId,
                ruleId: rule.ruleId
              });

              if (response && response.code === 0 && response.data && response.data.length > 0) {
                const relationId = response.data[0].id;
                if (relationId) {
                  const relDelResponse = await deleteRuleListRule(relationId);
                  if (relDelResponse && relDelResponse.code === 0) {
                    success = true;
                  } else {
                    success = false;
                    this.$message.error(relDelResponse.msg || '关联关系删除失败');
                  }
                }
              }
            } catch (error) {
              console.error('删除规则关联出错:', error);
              success = false;
              this.$message.error('删除规则关联出错');
            }
          }
        }

        // 如果操作成功，从界面上移除规则
        if (success) {
          // 从规则列表中移除
          const index = this.reviewCheckList.findIndex(item => item.ruleId === rule.ruleId);
          if (index !== -1) {
            this.reviewCheckList.splice(index, 1);
          }

          const actionText = rule.ruleSource === 'create' ? '删除' : '移除';
          this.$message.success(`${actionText}成功`);
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('操作规则出错:', error);
          this.$message.error('操作失败');
        }
      }
    },

    /**
     * Start progress simulation for a rule
     * @param {Object} rule - The rule object to simulate progress for
     */
    startProgressSimulation(rule) {
      if (!rule) return;

      // Initialize progress if not set
      if (!rule.progress) {
        rule.progress = 0;
      }

      // Create interval to increment progress
      const intervalId = setInterval(() => {
        // Increment progress more slowly as it gets higher
        const increment = Math.max(1, Math.floor((100 - rule.progress) / 10));
        rule.progress = Math.min(95, rule.progress + increment);

        // Force component update
        this.$forceUpdate();
      }, 1000);

      // Store interval ID for cleanup
      this.progressIntervals.set(rule.ruleId, intervalId);
    },

    /**
     * Stop progress simulation for a rule
     * @param {Object} rule - The rule object to stop progress simulation for
     */
    stopProgressSimulation(rule) {
      if (!rule) return;

      // Clear the interval
      const intervalId = this.progressIntervals.get(rule.ruleId);
      if (intervalId) {
        clearInterval(intervalId);
        this.progressIntervals.delete(rule.ruleId);
      }

      // Set progress to 100% if successful, or 0 if failed
      rule.progress = rule.status === 'completed' ? 100 : 0;

      // Force component update
      this.$forceUpdate();
    },

    /**
     * 接受风险修改建议
     * @param {Object} risk - 风险对象
     * @param {Number} index - 风险索引
     */
    acceptRisk(risk, index) {
      if (!risk || !risk.resultContent) {
        this.$message.warning('该风险点没有修改建议');
        return;
      }

      // 更新风险状态
      if (this.reviewResult.apiData && this.reviewResult.apiData.subRisks) {
        const riskItem = this.reviewResult.apiData.subRisks.find(r =>
          r.riskBrief === risk.riskBrief &&
          r.originalContent === risk.originalContent
        );

        if (riskItem) {
          riskItem.accept = true;

          // 更新接受数量
          if (this.reviewResult.apiData.subRiskAcceptNum !== undefined) {
            this.reviewResult.apiData.subRiskAcceptNum++;
          } else {
            this.reviewResult.apiData.subRiskAcceptNum = 1;
          }

          this.$message.success('已接受修改建议');
        }
      }
    },

    /**
     * 忽略风险
     * @param {Object} risk - 风险对象
     * @param {Number} index - 风险索引
     */
    ignoreRisk(risk, index) {
      // 更新风险状态
      if (this.reviewResult.apiData && this.reviewResult.apiData.subRisks) {
        const riskItem = this.reviewResult.apiData.subRisks.find(r =>
          r.riskBrief === risk.riskBrief &&
          r.originalContent === risk.originalContent
        );

        if (riskItem) {
          riskItem.accept = false;

          this.$message.info('已忽略该风险点');
        }
      }
    },

    /**
     * 应用所有修改
     */
    applyAllChanges() {
      if (!this.reviewResult.apiData || !this.reviewResult.apiData.subRisks) {
        this.$message.warning('没有可应用的修改');
        return;
      }

      const risksWithChanges = this.reviewResult.apiData.subRisks.filter(
        risk => risk.resultContent && risk.relatedRisk === '存在风险'
      );

      if (risksWithChanges.length === 0) {
        this.$message.warning('没有可应用的修改');
        return;
      }

      // 将所有风险点标记为已接受
      risksWithChanges.forEach(risk => {
        risk.accept = true;
      });

      // 更新接受数量
      this.reviewResult.apiData.subRiskAcceptNum = risksWithChanges.length;

      this.$message.success(`已应用全部 ${risksWithChanges.length} 处修改`);
    },

    /**
     * 导出审查报告
     */
    exportReviewResult() {
      this.$message.success('审查报告导出功能正在开发中');
    },

    /**
     * 格式化API返回的结果数据
     * @param {Object} data - API返回的数据
     * @returns {Array} 格式化后的结果数组
     */
    formatResults(data) {
      if (!data) return [];

      // 如果已经是数组，直接返回
      if (Array.isArray(data)) return data;

      // 如果是对象，转换为数组
      if (typeof data === 'object') {
        // 尝试提取关键信息
        const results = [];

        // 处理新的API返回格式
        if (data.examineBrief || data.subRisks) {
          // 添加审查概述
          if (data.examineBrief) {
            results.push({
              type: 'summary',
              title: '审查要点',
              description: data.examineBrief,
              level: data.riskLevel || 'medium'
            });
          }

          // 处理子风险点
          if (data.subRisks && Array.isArray(data.subRisks)) {
            data.subRisks.forEach((risk, index) => {
              // 跳过空风险点
              if (risk.relatedRisk === '无风险' && !risk.originalContent && !risk.resultContent) {
                return;
              }

              results.push({
                type: 'risk',
                title: risk.riskBrief || `风险点 ${index + 1}`,
                description: risk.riskExplain || '',
                level: data.riskLevel || 'medium',
                originalContent: risk.originalContent || '',
                resultContent: risk.resultContent || '',
                relatedRisk: risk.relatedRisk || ''
              });
            });
          }

          // 如果没有子风险点但有审查结果
          if (data.examineResult && (!data.subRisks || data.subRisks.length === 0)) {
            results.push({
              type: 'result',
              title: '审查结果',
              description: data.examineResult,
              level: data.riskLevel || 'medium'
            });
          }
        } else {
          // 处理旧格式
          // 处理风险点
          if (data.risks && Array.isArray(data.risks)) {
            data.risks.forEach(risk => {
              results.push({
                type: 'risk',
                title: risk.title || '风险点',
                description: risk.description || risk.content || '',
                level: risk.level || 'medium'
              });
            });
          }

          // 处理建议
          if (data.suggestions && Array.isArray(data.suggestions)) {
            data.suggestions.forEach(suggestion => {
              results.push({
                type: 'suggestion',
                title: suggestion.title || '修改建议',
                description: suggestion.description || suggestion.content || '',
              });
            });
          }

          // 处理评论
          if (data.comments && Array.isArray(data.comments)) {
            data.comments.forEach(comment => {
              results.push({
                type: 'comment',
                title: comment.title || '审查评论',
                description: comment.description || comment.content || '',
              });
            });
          }
        }

        // 如果没有提取到结构化数据，尝试将整个对象作为一个结果
        if (results.length === 0) {
          results.push({
            type: 'result',
            title: '审查结果',
            description: JSON.stringify(data, null, 2),
          });
        }

        return results;
      }

      // 如果是字符串，尝试解析为JSON
      if (typeof data === 'string') {
        try {
          return this.formatResults(JSON.parse(data));
        } catch (e) {
          // 如果不是有效的JSON，作为纯文本返回
          return [{
            type: 'text',
            title: '审查结果',
            description: data
          }];
        }
      }

      // 默认返回空数组
      return [];
    },

    // 根据风险等级筛选列表
    filterByRiskLevel(level) {
      this.selectedRiskLevel = level;
    },

    // 更新获取审查结果的方法
    async fetchReviewResults() {
      try {
        const uploadInstance = axios.create({
          baseURL: 'http://localhost:8481',
          timeout: 0,
          headers: {
            Authorization: 'Bearer ' + (localStorage.getItem("token") || this.$store.state.token)
          }
        });

        const response = await uploadInstance.get('/api/contract-review-results/listAll', {
          params: {
            contractId: this.contractId
          },
          timeout: 1300000
        });

        if (response.data.code === 0) {
          this.reviewResult.apiData = response.data.data;
          this.$message.success('审查结果获取成功');
        } else {
          throw new Error(response.data.message || '获取审查结果失败');
        }
      } catch (error) {
        console.error('获取审查结果列表失败:', error);
        this.$message.error('获取审查结果失败: ' + (error.message || '未知错误'));
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.contract-review {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f8fa;

  .top-nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    padding: 0 16px;
    background-color: #fff;
    border-bottom: 1px solid #e8e8e8;

    .nav-left {
      display: flex;
      align-items: center;

      .back-button {
        display: flex;
        align-items: center;
        padding: 0 12px;
        height: 32px;
        font-size: 13px;
        color: #606266;
        cursor: pointer;
        margin-right: 10px;

        &:hover {
          color: #409EFF;
        }

        i {
          margin-right: 4px;
        }
      }

      .nav-item {
        display: flex;
        align-items: center;
        padding: 0 12px;
        height: 32px;
        font-size: 13px;
        color: #1d2129;
        cursor: pointer;

        &.active {
          color: #165dff;
          background-color: #e8f3ff;
          border-radius: 4px;
        }

        i {
          margin-right: 6px;
        }
      }
    }

    .nav-right {
      display: flex;
      align-items: center;

      .el-button {
        margin-right: 16px;
      }

      .step {
        display: flex;
        align-items: center;
        margin-left: 16px;

        &.active {
          .step-num {
            background-color: #165dff;
            color: #fff;
          }

          .step-text {
            color: #165dff;
          }
        }

        .step-num {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          background-color: #e5e6eb;
          color: #86909c;
          font-size: 12px;
          margin-right: 8px;
        }

        .step-text {
          font-size: 14px;
          color: #86909c;
        }
      }
    }
  }

  .main-content {
    display: flex;
    flex: 1;
    overflow: hidden;

    .editor-area {
      flex: 1;
      display: flex;
      flex-direction: column;
      background-color: #fff;
      margin: 16px 0 16px 16px;
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      overflow: hidden;

      .editor-tabs {
        display: flex;
        height: 40px;
        border-bottom: 1px solid #e8e8e8;

        .tab {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 16px;
          height: 100%;
          font-size: 14px;
          color: #86909c;
          cursor: pointer;

          &.active {
            color: #165dff;
            border-bottom: 2px solid #165dff;
          }
        }
      }

      .editor-toolbar {
        display: flex;
        align-items: center;
        height: 40px;
        padding: 0 8px;
        border-bottom: 1px solid #e8e8e8;

        .toolbar-group {
          display: flex;
          align-items: center;

          i {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 28px;
            height: 28px;
            font-size: 16px;
            color: #4e5969;
            cursor: pointer;

            &:hover {
              background-color: #f2f3f5;
              border-radius: 4px;
            }
          }

          .font-selector, .font-size {
            display: flex;
            align-items: center;
            height: 28px;
            padding: 0 8px;
            font-size: 12px;
            color: #4e5969;
            cursor: pointer;

            i {
              width: auto;
              margin-left: 4px;
            }

            &:hover {
              background-color: #f2f3f5;
              border-radius: 4px;
            }
          }
        }

        .toolbar-separator {
          width: 1px;
          height: 16px;
          background-color: #e8e8e8;
          margin: 0 8px;
        }
      }

      .editor-content {
        flex: 1;
        overflow: auto;
        padding: 40px;

        .document-container {
          height: 100%;
          overflow-y: auto;
          padding: 20px;
          background-color: #f5f7fa;

          /* 文档样式 */
          :deep(h1) {
            font-size: 24px;
            font-weight: bold;
            margin: 20px 0 10px 0;
            color: #1f2329;
          }

          :deep(h2) {
            font-size: 20px;
            font-weight: bold;
            margin: 16px 0 8px 0;
            color: #1f2329;
          }

          :deep(h3) {
            font-size: 18px;
            font-weight: bold;
            margin: 14px 0 7px 0;
            color: #1f2329;
          }

          :deep(p) {
            margin: 10px 0;
            line-height: 1.6;
            color: #4e5969;
          }

          :deep(table) {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;

            th, td {
              border: 1px solid #dcdfe6;
              padding: 8px 12px;
            }

            th {
              background-color: #eef2f7;
              font-weight: bold;
            }
          }

          :deep(ul), :deep(ol) {
            margin: 10px 0 10px 20px;

            li {
              margin: 5px 0;
              color: #4e5969;
            }
          }

          :deep(a) {
            color: #165dff;
            text-decoration: none;

            &:hover {
              text-decoration: underline;
            }
          }

          :deep(blockquote) {
            border-left: 4px solid #dcdfe6;
            padding: 10px 15px;
            margin: 10px 0;
            background-color: #f7f8fa;
            color: #606266;
          }
        }

        .loading-container {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;

          .loading-spinner {
            font-size: 40px;
            color: #165dff;
            margin-bottom: 16px;
            animation: spin 1.5s linear infinite;
            width: 40px;
            height: 40px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #165dff;
            border-radius: 50%;
          }

          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }

          .loading-text {
            font-size: 14px;
            color: #86909c;
          }
        }

        .error-container {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;

          .error-icon {
            font-size: 40px;
            color: #165dff;
            margin-bottom: 16px;

            i {
              font-size: 40px;
            }
          }

          .error-message {
            font-size: 14px;
            color: #86909c;
            margin-bottom: 20px;
            text-align: center;
            max-width: 300px;
          }
        }
      }

      .editor-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 36px;
        padding: 0 16px;
        border-top: 1px solid #e8e8e8;
        background-color: #f7f8fa;

        .footer-left, .footer-right {
          display: flex;
          align-items: center;

          i {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            font-size: 14px;
            color: #4e5969;
            cursor: pointer;
            margin-right: 8px;

            &:hover {
              background-color: #e8e8e8;
              border-radius: 4px;
            }
          }

          .page-info, .word-info, .para-info, .line-info, .word-count {
            font-size: 12px;
            color: #86909c;
            margin-right: 12px;
          }

          .zoom {
            display: flex;
            align-items: center;
            font-size: 12px;
            color: #86909c;
            margin-right: 12px;

            span {
              margin: 0 4px;
            }
          }
        }
      }
    }

    .review-area {
      flex: 1;
      display: flex;
      flex-direction: column;
      background-color: #fff;
      margin: 16px 16px 16px 8px;
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      overflow: auto;

      .content-wrapper {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding: 16px;
      }

      .steps-nav {
        display: flex;
        align-items: center;
        margin-bottom: 24px;
        padding: 16px 0;

        .step {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-right: 16px;
          position: relative;
          z-index: 1;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            .step-text {
              color: #165dff;
            }
          }

          &.active {
            .step-circle {
              background-color: #165dff;
              color: #fff;
            }

            .step-text {
              color: #165dff;
            }
          }

          .step-circle {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background-color: #e5e6eb;
            color: #86909c;
            font-size: 12px;
            margin-bottom: 8px;
          }

          .step-text {
            font-size: 14px;
            color: #86909c;
          }
        }

        .step-line {
          flex: 1;
          height: 1px;
          background-color: #e8e8e8;
          margin: 0 8px;
          position: relative;
          top: -8px;
        }
      }

      .review-section {
        margin-bottom: 24px;
        background-color: #f9fafc;
        padding: 16px;
        border-radius: 4px;

        .section-title {
          font-size: 16px;
          font-weight: 500;
          color: #1d2129;
          margin-bottom: 16px;
          padding-bottom: 8px;
          border-bottom: 1px solid #e8e8e8;
        }

        .form-item {
          margin-bottom: 16px;
          display: flex;
          flex-direction: column;

          label {
            font-size: 14px;
            color: #1d2129;
            margin-bottom: 8px;
          }

          .el-select, .el-radio-group {
            width: 100%;
          }
        }

        .form-buttons {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 8px;

          .ai-generate-btn, .knowledge-btn {
            flex: 1;
            height: 36px;
            margin: 0 8px;

            &:first-child {
              margin-left: 0;
            }

            &:last-child {
              margin-right: 0;
            }
          }
        }
      }

      .contract-info {
        margin-bottom: 16px;

        .info-item {
          margin-bottom: 16px;
          border-bottom: 1px dashed #e8e8e8;
          padding-bottom: 8px;

          &:last-child {
            margin-bottom: 0;
            border-bottom: none;
          }

          .info-label {
            font-size: 14px;
            font-weight: 500;
            color: #1d2129;
            margin-bottom: 8px;
          }

          .info-value {
            font-size: 14px;
            color: #4e5969;
            line-height: 1.6;
          }

          .content-overview {
            line-height: 1.6;
            max-height: 120px;
            overflow-y: auto;
            text-align: justify;
            background-color: #f5f7fa;
            padding: 8px;
            border-radius: 4px;
          }
        }
      }

      .form-input {
        .el-radio {
          margin-right: 16px;
          margin-bottom: 0;
        }
      }

      .pro-tag {
        display: inline-block;
        font-size: 12px;
        color: #165dff;
        background-color: #e8f3ff;
        padding: 0 4px;
        border-radius: 2px;
        margin-left: 4px;
      }

      .checklist-content {
        .checklist-items {
          .checklist-item {
            background-color: #fff;
            padding: 12px;
            border-radius: 4px;
            margin-bottom: 12px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);

            .item-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;

              .item-left {
                display: flex;
                align-items: center;

                .item-checkbox {
                  margin-right: 8px;
                }

                .item-number {
                  font-size: 14px;
                  color: #909399;
                  background-color: #f0f2f5;
                  border-radius: 3px;
                  padding: 0 6px;
                  margin-right: 8px;
                  min-width: 24px;
                  text-align: center;
                }

                .item-title {
                  font-size: 15px;
                  font-weight: 500;
                  color: #1d2129;
                }

                .self-created-tag {
                  display: inline-block;
                  padding: 0 5px;
                  height: 20px;
                  line-height: 20px;
                  font-size: 12px;
                  color: #fff;
                  background-color: #f56c6c;
                  border-radius: 2px;
                  margin-left: 8px;
                  white-space: nowrap;
                }

                .generate-tag {
                  display: inline-block;
                  padding: 0 5px;
                  height: 20px;
                  line-height: 20px;
                  font-size: 12px;
                  color: #fff;
                  background-color: #67c23a;
                  border-radius: 2px;
                  margin-left: 8px;
                  white-space: nowrap;
                }
              }

              .item-right {
                margin-left: 10px;
              }
            }

            .item-status {
              font-size: 12px;
              padding: 2px 8px;
              border-radius: 10px;

              &.pass {
                background-color: #f0f9eb;
                color: #67c23a;
              }

              &.fail {
                background-color: #fef0f0;
                color: #f56c6c;
              }

              &.warning {
                background-color: #fdf6ec;
                color: #e6a23c;
              }

              &.pending {
                background-color: #ecf5ff;
                color: #409eff;
              }
            }

            .item-description {
              font-size: 14px;
              color: #606266;
              line-height: 1.6;
            }

            .review-content {
              margin-top: 16px;
              padding: 16px;
              background-color: #f9fafc;
              border-radius: 4px;

              // 审查要点样式
              .review-summary {
                margin-bottom: 20px;
                padding: 16px;
                background-color: #fff;
                border-radius: 4px;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);

                .summary-item {
                  .summary-title {
                    font-size: 16px;
                    font-weight: 500;
                    color: #1d2129;
                    margin-bottom: 10px;
                  }

                  .summary-content {
                    font-size: 14px;
                    color: #606266;
                    line-height: 1.6;
                    white-space: pre-line;
                  }
                }
              }

              // 风险点列表样式
              .risk-list {
                margin-bottom: 20px;

                .risk-list-header {
                  display: flex;
                  align-items: center;
                  margin-bottom: 12px;

                  .risk-count {
                    font-size: 15px;
                    font-weight: 500;
                    color: #1d2129;
                    display: flex;
                    align-items: center;

                    i {
                      margin-left: 5px;
                      font-size: 12px;
                      color: #909399;
                    }
                  }
                }

                .risk-item-container {
                  margin-bottom: 16px;
                  padding: 16px;
                  background-color: #fff;
                  border-radius: 4px;
                  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);

                  &:last-child {
                    margin-bottom: 0;
                  }

                  .risk-item-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 12px;

                    .risk-item-title {
                      font-size: 15px;
                      font-weight: 500;
                      color: #1d2129;
                    }
                  }

                  .risk-item-content {
                    .risk-explanation {
                      font-size: 14px;
                      color: #606266;
                      line-height: 1.6;
                      margin-bottom: 16px;
                      white-space: pre-line;
                    }

                    .contract-text {
                      margin-bottom: 16px;
                      padding: 12px;
                      border-radius: 4px;

                      &.original {
                        background-color: #f5f7fa;
                        border-left: 3px solid #909399;
                      }

                      &.suggestion {
                        background-color: #f0f9eb;
                        border-left: 3px solid #67c23a;
                      }

                      .text-header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-bottom: 8px;

                        .text-label {
                          font-size: 13px;
                          font-weight: 500;
                          color: #606266;
                        }

                        .edit-btn {
                          padding: 0;
                          font-size: 12px;
                          color: #409EFF;
                        }
                      }

                      .text-content {
                        font-size: 14px;
                        color: #303133;
                        line-height: 1.6;
                        white-space: pre-line;
                      }
                    }
                  }
                }
              }

              // 其他类型结果样式
              .review-detail {
                margin-bottom: 16px;
                padding-bottom: 16px;
                border-bottom: 1px dashed #e8e8e8;

                &:last-child {
                  margin-bottom: 0;
                  padding-bottom: 0;
                  border-bottom: none;
                }

                .result-header {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin-bottom: 8px;

                  .result-title {
                    font-size: 14px;
                    font-weight: 500;
                    color: #1d2129;
                  }
                }

                .result-description {
                  font-size: 14px;
                  color: #606266;
                  line-height: 1.6;
                  white-space: pre-line;
                }
              }

              .empty-result {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 20px 0;

                i {
                  font-size: 24px;
                  color: #c0c4cc;
                  margin-bottom: 8px;
                }

                p {
                  font-size: 14px;
                  color: #909399;
                }
              }
            }
          }
        }

        .empty-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 40px 0;

          i {
            font-size: 48px;
            color: #c0c4cc;
            margin-bottom: 16px;
          }

          p {
            font-size: 14px;
            color: #909399;
            margin-bottom: 16px;
          }
        }
      }

      .result-content {
        // 新的审查结果样式
        .new-result-summary {
          // 风险统计
          .risk-statistics {
            display: flex;
            gap: 16px;
            margin-bottom: 24px;
            padding: 16px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

            .risk-stat-item {
              flex: 1;
              padding: 16px;
              border-radius: 8px;
              cursor: pointer;
              transition: all 0.3s ease;
              border: 1px solid #e8e8e8;
              position: relative;
              overflow: hidden;
              background: #fafafa;
              display: flex;
              align-items: center;
              justify-content: space-between;

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
              }

              &.active {
                border-color: transparent;
                color: #fff;

                &:before {
                  content: '';
                  position: absolute;
                  top: 0;
                  left: 0;
                  right: 0;
                  bottom: 0;
                  opacity: 0.1;
                  background: currentColor;
                }

                .stat-label {
                  color: inherit;
                }

                .stat-value {
                  color: inherit;
                }
              }

              &:nth-child(1).active {
                background: #1890ff;
              }

              &:nth-child(2).active {
                background: #ff4d4f;
              }

              &:nth-child(3).active {
                background: #faad14;
              }

              &:nth-child(4).active {
                background: #52c41a;
              }

              .stat-label {
                font-size: 14px;
                color: #909399;
              }

              .stat-value {
                font-size: 20px;
                font-weight: 500;
                line-height: 1;

                &.high-risk {
                  color: #ff4d4f;
                }

                &.medium-risk {
                  color: #faad14;
                }

                &.low-risk {
                  color: #52c41a;
                }
              }
            }
          }

          // 审查结果列表
          .review-results {
            .rule-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 10px;

              .rule-name {
                font-size: 16px;
                font-weight: 500;
                color: #1d2129;
              }

              .rule-status {
                .el-tag {
                  margin-left: 10px;
                }
              }
            }

            .examine-brief {
              margin-bottom: 10px;

              h4 {
                font-size: 14px;
                font-weight: 500;
                color: #606266;
                margin-bottom: 5px;
              }

              p {
                font-size: 14px;
                color: #909399;
                line-height: 1.6;
              }
            }

            .risk-points {
              .risk-item {
                margin-bottom: 20px;
                border: 1px solid #e8e8e8;
                border-radius: 8px;
                overflow: hidden;
                background: #fff;

                &.has-risk {
                  border-left: 4px solid #ff4d4f;
                }

                .risk-header {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  padding: 12px 16px;
                  background: #fafafa;
                  border-bottom: 1px solid #e8e8e8;

                  .risk-title-section {
                    display: flex;
                    align-items: center;
                    gap: 12px;
                  }

                  .risk-number {
                    width: 24px;
                    height: 24px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background: #f0f0f0;
                    border-radius: 12px;
                    font-size: 14px;
                    color: #666;
                  }

                  .risk-title {
                    font-size: 15px;
                    font-weight: 500;
                    color: #333;
                  }

                  .risk-status {
                    padding: 2px 8px;
                    border-radius: 4px;
                    font-size: 13px;

                    &.success {
                      background: #f6ffed;
                      color: #52c41a;
                      border: 1px solid #b7eb8f;
                    }

                    &.danger {
                      background: #fff2f0;
                      color: #ff4d4f;
                      border: 1px solid #ffccc7;
                    }
                  }
                }

                .risk-explanation {
                  padding: 16px;
                  background: #fffbe6;
                  border-bottom: 1px solid #f5e7b1;

                  .section-title {
                    font-weight: 500;
                    color: #d4b106;
                    margin-bottom: 8px;
                  }

                  .section-content {
                    color: #666;
                    line-height: 1.6;
                  }
                }

                .content-sections {
                  display: flex;
                  gap: 16px;
                  padding: 16px;

                  .original-content, .suggested-content {
                    flex: 1;
                    background: #f8f8f8;
                    border-radius: 6px;
                    padding: 12px;

                    .section-title {
                      font-weight: 500;
                      color: #666;
                      margin-bottom: 8px;
                      font-size: 14px;
                    }

                    .section-content {
                      color: #333;
                      line-height: 1.6;
                      font-size: 14px;
                      white-space: pre-wrap;
                    }
                  }

                  .suggested-content {
                    background: #f0f7ff;

                    .section-title {
                      color: #1890ff;
                    }
                  }
                }
              }
            }
          }
        }

        // 旧的审查结果样式 - 保留兼容性
        .result-summary {
          h4 {
            font-size: 16px;
            font-weight: 500;
            color: #1d2129;
            margin: 16px 0 12px 0;

            &:first-child {
              margin-top: 0;
            }
          }

          p {
            font-size: 14px;
            color: #606266;
            line-height: 1.6;
            margin-bottom: 16px;
          }

          .risk-item, .suggestion-item {
            background-color: #fff;
            padding: 12px;
            border-radius: 4px;
            margin-bottom: 12px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);

            .risk-title, .suggestion-title {
              font-size: 15px;
              font-weight: 500;
              color: #1d2129;
              margin-bottom: 8px;
            }

            .risk-description, .suggestion-description {
              font-size: 14px;
              color: #606266;
              line-height: 1.6;
            }
          }

          .risk-item {
            border-left: 4px solid #f56c6c;
          }

          .suggestion-item {
            border-left: 4px solid #67c23a;
          }
        }

        .empty-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 40px 0;

          i {
            font-size: 48px;
            color: #c0c4cc;
            margin-bottom: 16px;
          }

          p {
            font-size: 14px;
            color: #909399;
            margin-bottom: 16px;
          }
        }
      }

      .review-footer {
        display: flex;
        justify-content: flex-end;
        padding: 16px;
        border-top: 1px solid #e8e8e8;
        background-color: #f7f8fa;

        .review-btn {
          height: 36px;
        }
      }
    }
  }
}

.rule-list-select {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #e8e8e8;
}

.form-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 16px;

  .ai-generate-btn, .knowledge-btn {
    flex: 1;
    height: 48px;
    border-radius: 4px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:first-child {
      margin-right: 8px;
    }

    &:last-child {
      margin-left: 8px;
    }

    i {
      margin-right: 4px;
    }
  }

  .ai-generate-btn {
    background-color: #409eff;
    border-color: #409eff;
    color: #fff;

    &:hover, &:focus {
      background-color: #66b1ff;
      border-color: #66b1ff;
      color: #fff;
    }

    &.plain {
      &.el-button--primary {
        background-color: #409eff;
        color: #fff;
      }

      &.el-button--default {
        background-color: #f4f7fd;
        color: #409eff;
        border-color: #d9ecff;
      }
    }
  }

  .knowledge-btn {
    &.el-button--primary {
      background-color: #409eff;
      color: #fff;
    }

    &.el-button--default {
      background-color: #fff;
      color: #606266;
      border-color: #dcdfe6;
    }
  }
}

.custom-rule-btn-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.custom-rule-btn {
  width: 100%;
  height: 40px;
  border: 1px solid #f56c6c;
  color: #f56c6c;
  background-color: transparent;
  font-size: 14px;
  position: relative;

  &:hover {
    background-color: rgba(245, 108, 108, 0.1);
  }

  .pro-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background-color: #165dff;
    color: white;
    font-size: 10px;
    padding: 2px 4px;
    border-radius: 4px;
  }
}

/* 自定义规则对话框样式 */
:deep(.rule-edit-dialog) {
  margin: 0;
}

.rule-edit-container {
  padding: 0;
  min-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.rule-edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #EBEEF5;
  padding: 15px 20px;
}

.rule-edit-title {
  font-size: 18px;
  font-weight: bold;
}

.rule-edit-actions .el-button {
  margin-left: 10px;
}

.rule-edit-content {
  display: flex;
  flex: 1;
  height: calc(100vh - 120px);
}

.rule-edit-form {
  width: 50%;
  padding: 20px;
  overflow-y: auto;
}

.rule-edit-preview {
  width: 50%;
  padding: 20px;
  background-color: #f5f7fa;
  border-left: 1px solid #EBEEF5;
  overflow-y: auto;
}

.risk-level-group {
  display: flex;
  gap: 10px;
}

.risk-level-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px 20px;
  cursor: pointer;
  text-align: center;
  transition: all 0.3s;
}

.risk-level-item.active {
  color: #fff;
}

.high-risk.active {
  background-color: #F56C6C;
  border-color: #F56C6C;
}

.medium-risk.active {
  background-color: #E6A23C;
  border-color: #E6A23C;
}

.low-risk.active {
  background-color: #909399;
  border-color: #909399;
}

.preview-content {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.preview-header {
  margin-bottom: 20px;
}

.preview-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.preview-desc {
  color: #303133;
  line-height: 1.5;
}

.preview-section {
  margin-bottom: 20px;
}

.preview-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.preview-text {
  color: #303133;
  line-height: 1.6;
}

.checklist-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.checklist-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.select-all {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.save-to-new {
  display: flex;
  align-items: center;
}

.save-to-new .el-button {
  color: #409EFF;
  font-size: 14px;
}

.item-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.item-checkbox {
  margin-right: 8px;
}

.loading-review-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;

  i {
    font-size: 36px;
    color: #409EFF;
    margin-bottom: 16px;
  }

  p {
    font-size: 14px;
    color: #606266;
    margin-bottom: 8px;
  }

  .loading-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
    background-color: #f0f9eb;
    padding: 5px 10px;
    border-radius: 4px;
    border-left: 3px solid #67c23a;
  }
}

.review-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;

  .loading-text {
    font-size: 14px;
    color: #606266;
    margin-top: 16px;
    margin-bottom: 8px;
  }

  .loading-subtext {
    font-size: 12px;
    color: #909399;
    background-color: #f0f9eb;
    padding: 4px 8px;
    border-radius: 4px;
    border-left: 2px solid #67c23a;
  }
}
</style>
